using MediatR;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Menus.Commands.CreateMenu;

public class CreateMenuCommandHandler : IRequestHandler<CreateMenuCommand, ApiResult<MenuFlatDto>>
{
  private readonly IUnitOfWork _uow;
  private readonly ILogger<CreateMenuCommandHandler> _logger;

  public CreateMenuCommandHandler(IUnitOfWork uow, ILogger<CreateMenuCommandHandler> logger)
  {
    _uow = uow;
    _logger = logger;
  }

  public async Task<ApiResult<MenuFlatDto>> Handle(CreateMenuCommand request, CancellationToken ct)
  {
    try
    {
      // 业务校验：路径唯一
      if (!string.IsNullOrWhiteSpace(request.Dto.Path))
      {
        var exists = await _uow.MenuRepository.AnyAsync(m => m.Path == request.Dto.Path);
        if (exists)
          return ApiResult<MenuFlatDto>.Failure(400, $"路径 '{request.Dto.Path}' 已存在");
      }

      // 计算同级最大排序
      // var maxSort = await _uow.MenuRepository.CountAsync(m => m.ParentId == request.Dto.ParentId) + 1;

      var menu = Menu.Create(
          request.Dto.Name,
          request.Dto.Path,
          request.Dto.Icon,
          request.Dto.ParentId,
          request.Dto.Sort);


      await _uow.MenuRepository.AddAsync(menu);
      await _uow.SaveChangesAsync();

      var dto = new MenuFlatDto
      {
        Id = menu.Id,
        Name = menu.Name,
        Path = menu.Path,
        Icon = menu.Icon,
        ParentId = menu.ParentId,
        Sort = menu.Sort
      };

      return ApiResult<MenuFlatDto>.Success(dto, "菜单创建成功");
    }
    catch (Exception ex)
    {
      _logger.LogError(ex, "创建菜单失败");
      return ApiResult<MenuFlatDto>.Failure(500, "服务器内部错误");
    }
  }
}